package xj.controller.backstage;

import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheKit;

import xj.controller.base.BaseController;
import xj.model.SysUser;
import xj.service.backstage.LoginService;
import xj.utils.IPUtil;
import xj.utils.TimeUtil;

/**
 * 后台-登陆页面
 * @author zhangxudong
 *
 */
public class LoginController extends BaseController {
	
	@Inject
	private static LoginService service;

	@Clear
	public void index () {
		
		render("login/login.html");
	}
	
	@Clear
	public void loginCheck () {
		String usercode = get("usercode", "");
		String password = get("password", "");
		
		if (StrKit.isBlank(usercode) || StrKit.isBlank(password)) {
			renderErrorJson("9999", "用户名或密码错误！");
			return;
		}
		
		SysUser sysUser = service.loginCheck(usercode, password);
		if (sysUser == null) {
			renderErrorJson("9999", "用户名或密码错误！");
			return;
		}
		
		if(sysUser.getStr("status").equals("1")){
			renderErrorJson("9999", "用户名已注销！");
			return;
		}
		
		if(sysUser.getStr("status").equals("2")){
			renderErrorJson("9999", "用户名已锁定！"); 
			return;
		}
		
		sysUser.set("lastlogindate", sysUser.getStr("logindate"));
		sysUser.set("lastlogintime", sysUser.getStr("logintime"));
		sysUser.set("logindate", TimeUtil.getyyyyMMddTime());
		sysUser.set("logintime", TimeUtil.getHHmmssTime());
		sysUser.set("ipaddr", IPUtil.getFromIp(getRequest()));
		
		// return true 提交事务，return false 则回滚事务
		Db.tx(() -> {
			sysUser.update();
			try {
				setSessionAttr("usinfo", sysUser);
				CacheKit.put("usinfoCache", sysUser.getInt("userid"), getSession().getId());
			} catch (Exception e) {
//				e.printStackTrace();
				return false;
			}
			return true;
		});
		
		// 数据库字段用set  否则用put
			
		set("retcode", "0000");
		renderJson();
	}
	
}
